import type { ReactElement } from 'react';
import React, { useState } from 'react';
import { connect, useIntl } from 'umi';
import request from '@/utils/request';
import {
  List,
  Avatar,
  Button,
  Skeleton,
  Typography,
  Descriptions,
  Space,
  Slider,
  Row,
  Col,
  InputNumber,
  Checkbox,
  message,
  Modal,
  Radio,
  RadioChangeEvent,
  Image,
} from 'antd';
import UploadUtil from '@/components/UploadUtil';
import { ArrowLeftOutlined, ExclamationCircleFilled } from '@ant-design/icons';
import loadinggif from '../assets/loading.gif';

interface DataType {
  id?: number;
  productName?: string;
  imgUrl?: string;
  creationTime?: Date;
  lastModificationTime?: Date;
  buyCount: number;
  days: number;
  ium?: string;
  className?: string;
  memo?: string;
  unitPrice: number;
  discount: number;
  contents?: any;
  quantity: number;
  step: number;
  minNum: number;
  productType: number;
  payType: any;
}
const { confirm } = Modal;
const { Text } = Typography;
const pageSize: number = 10;
const apiURLReport = '/api/services/app/SysConfig/';
export interface FCProps {
  title?: string | ReactElement;
  callback?: (item: any) => void;
  currentConfig: any;
  freshNum?: number;
}
const AppMarket: React.FC<FCProps> = (props: FCProps) => {
  const intl = useIntl();
  const [initLoading, setInitLoading] = useState(true);
  const [loading, setLoading] = useState(false);
  const [pageCount, setPageCount] = useState<number>(1);
  const [pageIndex, setPageIndex] = useState<number>(1);
  const [dataSource, setDataSource] = useState<DataType[]>([]);
  const [isDetail, setIsDetail] = useState(false);
  const [datas, setDatas] = useState<DataType>({
    discount: 1,
    buyCount: 0,
    days: 0,
    step: 1,
    unitPrice: 0,
    minNum: 0,
    productType: 4,
    payType: 3,
    quantity: 0,
  });
  const [inputQty, setQuantity] = useState(1);
  const [agreeLaw, setAgreeLaw] = useState(false);
  const [amount, setAmount] = useState<number>(0);
  const [payType, setPayType] = useState<string>('0');
  const [visible, setVisible] = useState(false);
  const [qrCodeStr, setQRCosdeStr] = useState<string>('');
  const [tradeNo, setTradeNo] = useState<string>('');
  const [payTypeOptions, setPayTypeOptions] = useState<any[]>([]);

  const fetchData = () => {
    if (pageIndex > pageCount) {
      setLoading(false);
      setInitLoading(false);
      message.info(intl.formatMessage({ id: 'pages.nomore' }));
      return;
    }
    request(apiURLReport + 'GetProducts', {
      method: 'GET',
      params: {
        skipCount: (pageIndex - 1) * pageSize,
        maxResultCount: pageSize,
        enable: 1,
        className: 'ERP模块',
      },
    }).then((response) => {
      if (response) {
        if (response.success) {
          const res = response.result;
          const newData = dataSource.concat(res.items);
          setDataSource(newData);
          setLoading(false);
          setInitLoading(false);
          setPageCount(Math.abs(res.totalCount / pageSize));
          window.dispatchEvent(new Event('resize'));
        }
      }
    });
  };
  const pOption = [
    { label: '支付宝', value: '1', disabled: false, checked: false },
    { label: '微信', value: '2', disabled: false, checked: false },
    { label: '云金币', value: '3', disabled: false, checked: false },
  ];
  const getDetail = (visible: boolean, id: number = 0) => {
    setIsDetail(visible);
    if (id > 0) {
      request(apiURLReport + 'GetProductDetail', {
        method: 'GET',
        params: { id },
      }).then((response) => {
        if (response) {
          if (response.success) {
            const res = response.result;
            setDatas(res);
            setQuantity(res.minNum);
            setAmount(res.minNum * res.discount * res.unitPrice);

            const payTypeArr = res.payType ? JSON.parse(res.payType) : [];
            var arr: any = [];
            pOption.forEach((element) => {
              if (payTypeArr.indexOf(element.value) >= 0) {
                arr.push(element);
              }
            });
            setPayTypeOptions(arr);
          }
        }
      });
    }
  };
  const onChangeQty = (qty: number) => {
    setQuantity(qty);
    let amount =
      qty * (datas?.unitPrice ? datas?.unitPrice : 0) * (datas?.discount ? datas?.discount : 1);
    setAmount(amount);
  };
  const checkTiaoKuan = (e: any) => {
    setAgreeLaw(e.target.checked);
  };
  const goToBuy = () => {
    if (amount <= 0) {
      message.warning(intl.formatMessage({ id: 'pages.amount.required' }));
      return;
    }
    if (payType == '0') {
      message.warning(intl.formatMessage({ id: 'pages.paymethord.required' }));
      return;
    }
    if (props.currentConfig?.balance < amount && payType == '3') {
      message.warning(intl.formatMessage({ id: 'pages.balance.insufficient' }));
      return;
    }
    if (!agreeLaw) {
      confirm({
        title: intl.formatMessage({ id: 'pages.system.tip' }),
        icon: <ExclamationCircleFilled />,
        content: intl.formatMessage({ id: 'pages.agreeOperpServiceItem' }),
        onOk() {
          setAgreeLaw(true);
          createTrade();
        },
        onCancel() {
          return;
        },
      });
    } else {
      createTrade();
    }
  };
  const createTrade = () => {
    request(apiURLReport + 'CreateTradeAsync', {
      method: 'POST',
      data: {
        amount: amount,
        payDestination: datas?.productType,
        payType: payType,
        canInvoiced: true,
        productId: datas?.id,
        quantity: inputQty,
      },
    }).then((response) => {
      if (response && response.success) {
        const res = response.result.data;
        var p = payTypeOptions.filter((o) => o.value == payType.toString())[0];
        message.info('发起' + p.label + '支付');
        setTradeNo(res.tradeNo);
        if (payType == '3') {
          pushNotify(res.totalAmount, '', res.tradeNo, '');
        } else {
          //调用第三方支付
          request('/alipay/QRCodePay', {
            method: 'POST',
            data: {
              body: datas?.productName,
              subject: datas?.productName,
              totalAmount: amount.toString(),
              outTradeNo: res.tradeNo,
              productCode: datas?.id?.toString(),
              notifyUrl: 'https://m.oplug.cn:44352/api/AlipayNotify/AppPay',
            },
          }).then((resp) => {
            setQRCosdeStr(resp);
            setVisible(true);
          });
        }
      }
    });
  };
  const pushNotify = (totalAmount: number, tradeNo: string, outTradeNo: string, memo: string) => {
    request(apiURLReport + 'PushNotify', {
      method: 'POST',
      data: {
        totalAmount,
        tradeNo,
        outTradeNo,
        memo,
      },
    }).then((response) => {
      if (response && response.success) {
        const res = response.result;
        if (!res.success) {
          message.error(res.message);
        } else {
          message.info(intl.formatMessage({ id: 'pages.buySuccess' }) + datas?.productName);
        }
      }
    });
  };

  const isTradeSuccess = (tradeNo: string) => {
    request(apiURLReport + 'IsTradeSuccess', {
      method: 'POST',
      params: {
        tradeNo,
      },
    }).then((response) => {
      if (response) {
        if (response.result) {
          message.success(intl.formatMessage({ id: 'pages.trade.success' }));
          setVisible(false);
        } else {
          confirm({
            title: intl.formatMessage({ id: 'pages.system.tip' }),
            icon: <ExclamationCircleFilled />,
            content: intl.formatMessage({ id: 'pages.tradeFailAndClose' }),
            onOk() {
              setVisible(false);
            },
            onCancel() {
              return;
            },
          });
        }
      }
    });
  };
  React.useEffect(() => {
    fetchData();
  }, [props.freshNum]);
  const onLoadMore = () => {
    setPageIndex(pageIndex + 1);
    setLoading(true);
    fetchData();
  };
  const loadMore =
    !initLoading && !loading ? (
      <div
        style={{
          textAlign: 'center',
          marginTop: 12,
          height: 32,
          lineHeight: '32px',
        }}
      >
        <Button onClick={onLoadMore} disabled={pageIndex < pageCount}>
          {intl.formatMessage({ id: 'pages.load.more' })}
        </Button>
      </div>
    ) : null;
  const onChangePayType = ({ target: { value } }: RadioChangeEvent) => {
    setPayType(value);
  };

  return (
    <div>
      <div hidden={isDetail}>
        <List
          className="demo-loadmore-list"
          loading={initLoading}
          itemLayout="horizontal"
          loadMore={loadMore}
          dataSource={dataSource}
          renderItem={(item) => (
            <List.Item
              actions={[
                <a onClick={() => getDetail(true, item.id)} key="list-loadmore-edit">
                  {intl.formatMessage({ id: 'pages.buy' })}
                </a>,
                <a onClick={() => getDetail(true, item.id)} key="list-loadmore-more">
                  {intl.formatMessage({ id: 'pages.more.detail' })}
                </a>,
              ]}
            >
              <Skeleton avatar title={false} loading={loading} active>
                <List.Item.Meta
                  avatar={<Avatar src={UploadUtil.ossServDefault + item.imgUrl} />}
                  title={item.productName}
                  description={item.memo}
                />
                <div>
                  <Text type="danger">{item.unitPrice}</Text> 元 / {item.ium}
                </div>
              </Skeleton>
            </List.Item>
          )}
        />
      </div>
      <div hidden={!isDetail}>
        <Descriptions
          title={
            <div>
              <Avatar src={UploadUtil.ossServDefault + datas?.imgUrl} /> {datas?.productName}
            </div>
          }
          bordered
          column={3}
          extra={
            <Space>
              <span>
                <Checkbox onChange={(e: any) => checkTiaoKuan(e)} checked={agreeLaw} />{' '}
                {intl.formatMessage({ id: 'pages.hasReadAccept' })}
                <a>{intl.formatMessage({ id: 'pages.operpServiceItem' })}</a>
              </span>
              <Button type="ghost" onClick={() => getDetail(false)} icon={<ArrowLeftOutlined />}>
                {intl.formatMessage({ id: 'pages.back' })}
              </Button>
            </Space>
          }
        >
          <Descriptions.Item label={intl.formatMessage({ id: 'pages.totalSale' })}>{datas?.buyCount} </Descriptions.Item>
          <Descriptions.Item label={intl.formatMessage({ id: 'pages.category' })}>
            {datas?.className}
          </Descriptions.Item>
          <Descriptions.Item label={intl.formatMessage({ id: 'pages.updateTime' })}>
            {datas?.lastModificationTime?.toString()}
          </Descriptions.Item>
          <Descriptions.Item label={intl.formatMessage({ id: 'pages.unitPrice' })}>
            ￥{datas?.unitPrice} {intl.formatMessage({ id: 'pages.currencyUnit' })} / {datas?.ium}
          </Descriptions.Item>
          <Descriptions.Item label={intl.formatMessage({ id: 'pages.discount' })}>
            {datas?.discount < 1 ? datas?.discount * 10 + ' %' : ''}
          </Descriptions.Item>
          <Descriptions.Item label={intl.formatMessage({ id: 'pages.minOrderQty' })}>
            {datas?.minNum} {datas?.ium}
          </Descriptions.Item>
          <Descriptions.Item label={intl.formatMessage({ id: 'pages.product.detail' })}>
            <div dangerouslySetInnerHTML={{ __html: datas?.contents }}></div>
          </Descriptions.Item>
        </Descriptions>
        <Row gutter={[16, 16]}>
          <Col span={4}>
            <div style={{ textAlign: 'right', padding: '14px 0px 0px 0px' }}>
              <b>{intl.formatMessage({ id: 'pages.buyQty' })}：</b>
            </div>
          </Col>
          <Col span={10}>
            <div style={{ padding: '10px 0px' }}>
              <Slider
                min={datas?.minNum}
                max={datas?.quantity}
                step={datas?.step}
                onChange={onChangeQty}
                value={typeof inputQty === 'number' ? inputQty : 0}
              />
            </div>
          </Col>
          <Col span={4}>
            <InputNumber
              min={datas?.minNum}
              max={datas?.quantity}
              style={{ margin: '10px 0px', width: 120 }}
              step={datas?.step}
              value={inputQty}
              onChange={(val: any) => onChangeQty(val)}
              addonAfter={datas?.ium}
            />
          </Col>
          <Col span={6}></Col>
          <Col span={4}>
            <div style={{ textAlign: 'right' }}>
              <b>{intl.formatMessage({ id: 'pages.paymentMethod' })}：</b>
            </div>
          </Col>
          <Col span={8}>
            <Radio.Group options={payTypeOptions} onChange={onChangePayType} />
          </Col>
          <Col span={12}>
            <div style={{ textAlign: 'right' }}>
              <Space>
                <span>
                {intl.formatMessage({ id: 'pages.balance' })}：<Text type="warning">{props.currentConfig?.balance}</Text>
                </span>
                <span>
                  {intl.formatMessage({ id: 'pages.totalAmount' })}：￥
                  <Text type="danger">
                    <b>{amount.toFixed(2)}</b>
                  </Text>
                  {intl.formatMessage({ id: 'pages.currencyUnit' })}
                </span>
                <Button type="primary" danger onClick={() => goToBuy()}>
                  {intl.formatMessage({ id: 'pages.buy' })}
                </Button>
              </Space>
            </div>
          </Col>
        </Row>
        <Modal
          title={<b>{intl.formatMessage({ id: 'pages.paymentwindow' })}</b>}
          visible={visible}
          onOk={() => setVisible(false)}
          onCancel={() => setVisible(false)}
          footer={[
            <Button type="dashed" onClick={() => setVisible(false)}>
              {intl.formatMessage({ id: 'pages.pay.problem' })}
            </Button>,
            <Button type="primary" danger onClick={() => isTradeSuccess(tradeNo)}>
              {intl.formatMessage({ id: 'pages.pay.complete' })}
            </Button>,
          ]}
          destroyOnClose={true}
          mask
          width={450}
        >
          <Row gutter={[16, 16]}>
            <Col span={10}>
              <Image
                width={120}
                preview={false}
                src={UploadUtil.QRCodeServer + '?txt=' + encodeURIComponent(qrCodeStr) + '&pixel=2'}
                placeholder={
                  <div style={{ width: 120, height: 120, padding: 30 }}>
                    <Image preview={false} src={loadinggif} width={60} />
                  </div>
                }
              />
            </Col>
            <Col span={14}>
              <p>{intl.formatMessage({ id: 'pages.goodsName' })}：{datas?.productName}</p>
              <p>
              {intl.formatMessage({ id: 'pages.buyQty' })}：{inputQty} {datas?.ium}
              </p>
              <p>
              {intl.formatMessage({ id: 'pages.totalPayAmt' })}：
                <Text type="danger">
                  <b>{amount.toFixed(2)}</b>
                </Text>{' '}
                {intl.formatMessage({ id: 'pages.currencyUnit' })}
              </p>
            </Col>
          </Row>
        </Modal>
      </div>
    </div>
  );
};
//export default AppMarket;
export default connect(({ user }: API.IConnectState) => ({
  currentConfig: user.currentConfig,
}))(AppMarket);
